package org.hxzon.tapestry5.components;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.util.DateFormatUtil;

public class DateFormatter {

    @Parameter(required = true)
    private Object value;
    @Parameter(value = DateFormatUtil.UnitePattern_second, defaultPrefix = BindingConstants.LITERAL)
    private String format;
    @Inject
    private Locale locale;

    @BeginRender
    void beginRender(MarkupWriter writer) {
        if (value instanceof String) {
            String val = (String) value;
            val = val.substring(0, format.length());
            writer.write(val);
        }
        if (value instanceof Date) {
            SimpleDateFormat f = new SimpleDateFormat(format, locale);
            writer.write(f.format(value));
        }
    }
}
